#!/usr/bin/env python
# -*- coding:utf-8 -*-

import urllib

import tornado.ioloop
import tornado.ioloop
import tornado.web
import tornado.web
from concurrent.futures import ThreadPoolExecutor
from scpy.logger import get_logger
from tornado.concurrent import run_on_executor
from tornado.web import HTTPError

import che168_query
logger = get_logger(__file__)

MAX_WORKERS = 256
deal_encode = lambda argu: urllib.unquote(argu.strip().encode('utf-8'))


class IndexHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @run_on_executor
    def get(self):
        self.write('______')


class CarHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @run_on_executor
    def get(self):
        try:
            self.write(che168_query.search_price(
                specid=self.get_argument('carId', ''),
                cid=self.get_argument('cityId', ''),
                time=self.get_argument('time', ''),
                mileage=self.get_argument('mileage', ''))
            )
        except HTTPError, e:
            raise e


class QueryArgHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @run_on_executor
    def get(self, choosed):
        self.set_header('Content-Type', 'application/json; charset="utf-8"')
        if choosed.startswith('province'):
            self.write(che168_query.deal_province(choosed))
        elif choosed.startswith('car'):
            self.write(che168_query.deal_car(choosed))
        # self.write('       end')

SERVER_PORT = 7005

if __name__ == "__main__":
    application = tornado.web.Application(
        [
            (r'/', IndexHandler),
            (r'/car_price', CarHandler),
            (r'/pre_query/(.+)', QueryArgHandler),
        ], debug=False)
    application.listen(SERVER_PORT)
    logger.info('tornado server started on port %s', SERVER_PORT)
    tornado.ioloop.IOLoop.instance().start()

